package com.example.multi.common.handler;

import com.example.multi.common.common.CommonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

/**
 * @author: w.
 * @createTime: 2021-06-18 15:06
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = Exception.class)
    public CommonResponse commonExceptionHandle(Exception e) {

        CommonResponse commonResponse = CommonResponse.createCommonResponse();
        logger.error("error:{}", e);
        String error = (null == e || !StringUtils.hasText(e.getMessage())) ? "内部错误" : e.getMessage();
        //绑定错误
        if (e instanceof MethodArgumentNotValidException) {
            error = ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors().stream().map(i -> {
                StringBuilder item = new StringBuilder();
                item.append(i.getDefaultMessage());
                return item.toString();
            }).collect(Collectors.joining(","));
        }
        return commonResponse.fail("系统错误请稍后再试，原因:" + error);
    }

    @ModelAttribute
    public void addAttributes(Model model) {
        //model.addAttribute(GlobalConstants.START_TIME_KEY, System.nanoTime());
    }
}
